<template>
  <!-- 体检管理-新增 -->
  <div class="add_msg">
    <div class="base_msg">
      <mytitle>基本信息</mytitle>
      <el-input
        type="text"
        placeholder="请输入项目名称"
        v-model="text"
        maxlength="50"
        show-word-limit
      >
      </el-input>
      <el-select
        v-model="dictValue"
        placeholder="请输入项目单位, 如:ml(毫升)、m(米)、s(秒)等"
        clearable
      >
        <el-option
          v-for="item in company"
          :key="item.id"
          :label="item.dictValue"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <el-input
        type="textarea"
        placeholder="请输入内容"
        v-model="textarea"
        maxlength="500"
        :rows="5"
        show-word-limit
        resize="none"
      >
      </el-input>
    </div>
    <div class="config">
      <mytitle>得分规则</mytitle>
      <div v-for="(item, index) in test_data" :key="index" class="card_one">
        <el-card>
          <!-- 关闭按钮 -->
          <div class="close" @click="delete_class(index)">
            <img src="../../assets/imgs/icon_xtgb.png" alt="" />
          </div>
          <!-- 卡片表单 -->
          <el-form ref="form" :model="form" label-width="0.4167rem">
            <el-form-item label-width="0" style="margin-top: 0.0781rem">
              <el-select
                v-model="item.gradeId"
                placeholder="请选择年级"
                clearable
              >
                <el-option
                  v-for="item in gradeIds"
                  :key="item.id"
                  :label="item.gradeName"
                  :value="item.id"
                  @click.native="isGradeName(index, item.gradeName)"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label-width="0">
              <el-select v-model="item.sex" placeholder="全部">
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label-width="0">
              <el-select v-model="item.ruleType" placeholder="排序规则">
                <el-option label="成绩数值越小,得分越高" value="1"></el-option>
                <el-option label="成绩数值越大,得分越高" value="2"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label-width="0">
                            <el-input
                placeholder="该权重仅用于按照国家标准项目计算总分，非国家标准项目不可设置"
                v-model="item.weight"
                type="number"
              >
                                <template slot="append">%</template>
                              </el-input
              >
                          </el-form-item
            >

            <hr
              width="100%"
              style="border: 0.0052rem dashed #f4f4f4; height: 0.0104rem"
            />
            <el-form-item
              v-for="(items, indexs) in item.ruleItemList"
              :key="indexs"
              label-width="0"
              class="input_select"
            >
              <el-input
                v-model="items.score"
                placeholder="分数"
                style="width: 10%; height: 0.2604rem; margin-right: 0.0365rem"
              ></el-input>
              <el-input
                v-model="items.scoreValue"
                placeholder="最大值"
                style="
                  width: 18%;
                  height: 0.2604rem;
                  margin: 0 0.1042rem 0 0.1042rem;
                "
                @keyup.native="proving(items.scoreValue)"
              >
              </el-input>
              <el-select
                v-model="items.name"
                style="width: 17%; margin-right: 0.1042rem"
                placeholder="请选择等级"
              >
                <el-option
                  v-for="item in ranks"
                  :key="item.value"
                  :label="item.rank"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-input
                v-model="items.comment"
                placeholder="请输入评语"
                style="width: 45%; height: 0.2604rem"
              ></el-input>
              <i
                class="el-icon-circle-plus-outline"
                style="
                  font-size: 0.1042rem;
                  color: #44c68f;
                  margin-left: 0.0521rem;
                "
                v-if="indexs == 0"
                @click="addRule(index)"
              ></i>
              <i
                class="el-icon-remove-outline"
                style="
                  font-size: 0.1042rem;
                  color: #d9001b;
                  margin-left: 0.0521rem;
                "
                v-else
                @click="delRule(index, indexs)"
              ></i>
            </el-form-item>
            <el-alert
              title="60分以下以最低等级处理 , 即 : 具体得分按照测试成绩区间比例计算得出"
              type="warning"
              :closable="false"
              show-icon
            >
            </el-alert>
            <div
              class="addAch"
              v-if="item.isAddAchVal"
              @click="isAddAch(index)"
            >
              <i class="el-icon-plus"></i>
              <span>加分项</span>
            </div>
            <div v-else>
              <el-form-item
                v-for="(items, indexse) in item.plusesList"
                :key="indexse + 1"
                label-width="0"
                class="input_select"
              >
                <el-input
                  v-model="items.score"
                  placeholder="加分"
                  style="width: 20%; height: 0.2604rem; margin-right: 0.0365rem"
                ></el-input>
                <el-input
                  v-model="items.bonusValue"
                  placeholder="超过满分部分的成绩"
                  style="width: 70%; height: 0.2604rem; margin-right: 0.0365rem"
                  :prefix-icon="item.ruleType == 1 ? 'el-icon-minus':  'el-icon-plus'"
                ></el-input>
                <i
                  class="el-icon-circle-plus-outline"
                  style="
                    font-size: 0.1042rem;
                    color: #44c68f;
                    margin-left: 0.0521rem;
                  "
                  v-if="indexse == 0"
                  @click="addfen(index, indexse)"
                ></i>
                <i
                  class="el-icon-remove-outline"
                  style="
                    font-size: 0.1042rem;
                    color: #d9001b;
                    margin-left: 0.0521rem;
                  "
                  v-else
                  @click="delefen(index, indexse)"
                ></i>
              </el-form-item>
            </div>
          </el-form>
        </el-card>
      </div>
      <el-button @click="add_class">添加</el-button>
    </div>
    <div
      class="tijian_add button_add"
      style="position: fixed; left: 0; bottom: 0; width: 100%"
    >
      <div class="btnBox">
        <el-button @click="back">取消</el-button>
        <el-button @click="add">{{
          this.$route.query.type == 1 ? "修改" : "新增"
        }}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import mytitle from '../../components/title'
import { addExamine, getAllGardas, getCompany } from '@/api/index'
import { removeTab } from '@/api/delTab.js'
export default {
  name: 'addMessage',
  components: {
    mytitle
  },
  data() {
    return {
      // 切换加分项
      isAddAchVal: false,
      select: '',
      score: '',
      test_data: [
        {
          gradeId: '', gradeName: '', sex: '', weight: '', ruleType: '', ruleItemList: [
            { score: '', scoreValue: '', name: '', comment: '' }
          ],
          plusesList: [],
          isAddAchVal: true
        }
      ],
      text: '',
      textarea: '',
      // 项目成绩单位----------------------------
      company: [],
      dictValue: '',
      // ------------------
      ranks: [{
        value: 1,
        rank: '优秀'
      }, {
        value: 2,
        rank: '良好'
      }, {
        value: 3,
        rank: '及格'
      }, {
        value: 4,
        rank: '不及格'
      }],
      form: {
        stuClass: [],
        gender: '',
        ymin: '',
        ymax: '',
        yinput: '',
        lmin: '',
        lmax: '',
        linput: '',
        jmin: '',
        jmax: '',
        jinput: '',
        bmin: '',
        bmax: '',
        binput: ''
      },
      gradeIds: [],
      dynamicTags: ['标签一', '标签二', '标签三'],
      inputVisible: false,
      inputValue: '',
      examineInfo: [],
      allRuleList: []
    }
  },
  created() {

    this.getGarda()  //年级
    this.getCompanyList()  //单位


  },

  methods: {

    // 单位------------------------------
    async getCompanyList() {
      const res = await getCompany()
      this.company = res.data.data
      console.log('getCompany', res);
    },
    // 年级函数---------------------------
    async getGarda() {
      const data = {
        orgId: JSON.parse(sessionStorage.getItem('userMsg')).orgCode,
        gradeType: JSON.parse(localStorage.getItem('gradeType'))
      }
      const res = await getAllGardas(data)
      console.log('年级:', res);
      this.gradeIds = res.data.data
    },
    selectGradeId(gradeIdVal) {
      this.gradeId = gradeIdVal
      this.getExamTable()
    },
    // 选中的年级名称
    isGradeName(index, isGName) {
      console.log('选择年级传的id', index, isGName);
      this.test_data[index].gradeName = isGName
    },
    // ---------------------------------
    // 新增规则
    addRule(cardIdx) {
      var obj = { score: '', scoreValue: '', name: '', comment: '' }
      this.test_data[cardIdx].ruleItemList.push(obj)
    },
    delRule(cardIdx, ruleIdx) {
      this.test_data[cardIdx].ruleItemList.splice(ruleIdx, 1)
    },

    // 新增加分项
    addfen(e, l) {
      if (this.test_data[e].plusesList.length == 30) {
        this.$message({
          type: 'warning',
          message: '新增条数不能超过30条!'
        });
      }
      console.log(e, l);
      var obj = { score: '', bonusValue: '' };
      this.test_data[e].plusesList.push(obj);

    },
    delefen(e, l) {
      console.log(e, l);
      this.test_data[e].plusesList.splice(l, 1);
    },
    // 加分项切换
    isAddAch(e) {

      for (var i in this.test_data) {
        e == i ? this.test_data[i].isAddAchVal = false : ''
      }

      console.log('66666', e, this.test_data);

      var obj = { score: '', bonusValue: '' };
      this.test_data[e].plusesList.push(obj);

    },
    // -------------------------------------
    add_class() {
      var obj = {
        gradeId: '', gradeName: '', sex: '', ruleType: '', weight: '', ruleItemList: [
          { score: '', scoreValue: '', name: '', comment: '' },

        ],
        plusesList: [],
        isAddAchVal: true
      }
      this.test_data.push(obj)
    },
    delete_class(i) {
      this.test_data.splice(i, 1)
    },
    // 正则校验
    proving(value) {
      // value = 
    },
    // 体检新增
    async addExamineInfo() {
      const data = {
        orgId: JSON.parse(sessionStorage.getItem('userMsg')).orgCode,
        name: this.text,
        unit: this.dictValue,
        remark: this.textarea,
        ruleList: this.test_data
      }
      const res = await addExamine(data)
      console.log('体检新增', res);
      if (res.data.errorCode == 0) {
        this.$message({
          type: 'success',
          message: '新增成功!'
        });
        setTimeout(() => {
          // this.$router.push({ path: '/examination' })
          removeTab(this.$store.state.common.mainTabsActiveName)
        }, 1000);
      } else {
        this.$message({
          type: 'error',
          message: res.data.errorMsg
        });
      }
    },
    // 添加
    add() {
      var arr = this.test_data // 卡片数组
      if (this.text == '') {
        this.$message({
          type: 'warning',
          message: '项目名称不能为空'
        });
        return;
      }
      // if (this.dictValue == '') {
      //   this.$message({
      //     type: 'warning',
      //     message: '请选择项目单位'
      //   });
      //   return;
      // }

      for (var s in arr) {
        if (arr[s].gradeId == '' || arr[s].sex == '' || arr[s].ruleType == '') {
          this.$message({
            type: 'warning',
            message: '请完整填写得分规则'
          });
          return;
        }
        console.log(222)
        for (var o in arr[s].ruleItemList) {
          if (arr[s].ruleItemList[o].score == '' || arr[s].ruleItemList[o].scoreValue == '' || arr[s].ruleItemList[o].name == '') {
            this.$message({
              type: 'warning',
              message: '请完整填写得分规则'
            });
            return;
          }
        }
      }

      var brr = JSON.parse(JSON.stringify(arr))
      var crr = JSON.parse(JSON.stringify(arr))
      console.log('brr,crr', brr, crr);
      for (const i in brr) {
        if (brr[i].ruleType == 1) { // ruleType = 1 成绩越小，得分越高
          if (JSON.stringify(brr[i].ruleItemList.sort((a, b) => { return a.scoreValue - b.scoreValue })) === JSON.stringify(crr[i].ruleItemList)) {
            console.log('成绩越小', JSON.stringify(brr[i].ruleItemList.sort((a, b) => { return a.scoreValue - b.scoreValue })), JSON.stringify(crr[i].ruleItemList));
          } else {
            this.$message({
              type: 'error',
              message: '修改失败!请按照排序规则进行成绩排序！'
            });
            return
          }
        } else if (brr[i].ruleType == 2) { // ruleType = 1 成绩越高，得分越高
          if (JSON.stringify(brr[i].ruleItemList.sort((a, b) => { return b.scoreValue - a.scoreValue })) === JSON.stringify(crr[i].ruleItemList)) {
            console.log('成绩越高', JSON.stringify(brr[i].ruleItemList.sort((a, b) => { return b.scoreValue - a.scoreValue })), JSON.stringify(crr[i].ruleItemList));
          } else {
            this.$message({
              type: 'error',
              message: '修改失败!请按照排序规则进行成绩排序！'
            });
            return
          }
        } else {
          this.$message({
            type: 'error',
            message: '修改失败!请选择排序！'
          });
          return
        }
      }
      this.addExamineInfo()
    },
    // 取消
    back() {
      this.$confirm('此操作将不保存该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeTab(this.$store.state.common.mainTabsActiveName)
      }).catch(() => {

      });
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },

  },
  watch: {
    $route(val) {
      console.log(val, "333333333333333");
      var type = val.query.type;
      this.text = ''
      this.dictValue = ''
      this.textarea = ''
      this.test_data = [
        {
          gradeId: '', sex: '', ruleType: '', weight: '', ruleItemList: [
            { score: '', scoreValue: '', name: '', comment: '' }
          ],
          plusesList: [],
          isAddAchVal: true
        }
      ]
    },
  },
  mounted() {

  }
}
</script>

<style lang="scss" scoped>
.card_one {
  margin-bottom: 0.1042rem;
}
.add_msg {
  padding: 0.1979rem 0.1823rem;
  background-color: #fff;
  border-radius: 0.0781rem;
  // 基本信息
  .base_msg {
    padding-bottom: 0.2604rem;
    .el-input {
      margin-bottom: 0.1563rem;
    }
    .el-select {
      margin-bottom: 0.1563rem;
    }
    .el-input--medium .el-input__inner {
      background-color: #f7fbfc;
    }
  }
  // 得分规则
  .config {
    .el-card {
      border-radius: 0.0781rem;
      border: 0.0052rem solid #f2f2f2;
      padding: 0.125rem;
      position: relative;
      .close {
        width: 0.125rem;
        height: 0.125rem;
        position: absolute;
        right: 0.1302rem;
        top: 0.0833rem;
        margin-bottom: 0.0521rem;
        &:hover {
          cursor: pointer;
        }
      }
      /deep/.el-form-item:nth-child(1) .el-form-item__content {
        margin-top: 0.1042rem;
      }
      /deep/.el-select > .el-input--medium > .el-input__inner,
      /deep/.el-input .el-input__count .el-input__count-inner {
        background-color: #f7fbfc;
        line-height: 0.25rem;
      }
      /deep/.el-input-group--append .el-input__inner,
      /deep/.el-input-group__prepend {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
        border-top-left-radius: 0.0781rem;
        border-bottom-left-radius: 0.0781rem;
        font-size: 0.0625rem;
      }
      /deep/.el-input-group__append,
      .el-input-group__prepend {
        background-color: #f7fbfc;
        border: none;
        border-top-right-radius: 0.0781rem;
        border-bottom-right-radius: 0.0781rem;
        padding: 0 0.0521rem 0 0;
      }
      i:hover {
        cursor: pointer;
      }
      .addAch {
        width: 0.5208rem;
        margin: 0.1042rem 0 0.0521rem;
        color: #0fdd8d;
        font-size: 0.1042rem;
        &:hover {
          cursor: pointer;
        }
      }
    }
    .el-button {
      border-radius: 0.0521rem;
      border: 0.0052rem solid #0fdd8d;
      width: 0.7813rem;
      height: 0.2604rem;
      font-size: 0.0938rem;
      font-weight: 400;
      color: #0fdd8d;
      line-height: 0.1302rem;
      margin: 0.2083rem 0 0.625rem 0.0573rem;
      &:hover {
        background-color: #0fdd8d;
        color: #fff;
      }
    }
  }
}

/deep/.el-tag .el-icon-close {
  right: 0.3802rem;
  display: inline-block;
  width: 0.125rem;
  height: 0.125rem;
}

.el-select {
  width: 100%;
  height: 0.2604rem;
}
/deep/.el-input .el-input__count .el-input__count-inner {
  background-color: #f7fbfc;
  line-height: 0.25rem;
}
/deep/.el-input > .el-input__inner {
  background-color: #f7fbfc;
  height: 0.2604rem;
}
/deep/.el-textarea > .el-textarea__inner {
  background-color: #f7fbfc;
  line-height: 0.1563rem;
}
/deep/.el-textarea .el-input__count {
  background-color: rgba($color: #000000, $alpha: 0);
}
.el-card.is-always-shadow,
.el-card.is-hover-shadow:focus,
.el-card.is-hover-shadow:hover {
  box-shadow: none;
}
</style>
